package com.abel.quiz.interceptors;/**
 * Created by abel.lin on 2017/2/8.
 */

import com.abel.quiz.common.Constants;
import com.abel.quiz.common.widget.CaptchaUtils;

import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author abel.lin
 * @date_time 2017/2/8 14:31
 * @description
 */
public class CaptchaServlet extends HttpServlet implements Servlet {
    public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");

        //生成随机字串
        String verifyCode = CaptchaUtils.generateVerifyCode(4);
        //存入会话session
        HttpSession session = request.getSession(true);
        session.setAttribute(Constants.captchaCode, verifyCode.toLowerCase());
        //生成图片
        int w = 200, h = 80;
        CaptchaUtils.outputImage(w, h, response.getOutputStream(), verifyCode);

    }
}
